/**
 * Created by tanbingqin on 2019/12/17.
 */
import {messages} from "share/common";
import React from 'react'
import { connect } from 'react-redux'
import { message, Button, Spin, Icon, Badge, Popconfirm } from 'antd'
import moment from 'moment';
import menuRoute from 'routes/menuRoute'
import errorMessage from 'share/errorMessage';
import ResizeTable from 'components/resize-table'

import agencyService from 'containers/setting/agency-setting/agency-setting.service'
import 'styles/setting/agency-setting/agency-detail.scss'
import SlideFrame from 'components/slide-frame'
import NewProxy from 'containers/setting/agency-setting/new-proxy'

class AgencyDetailV2 extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      pageLoading: false,
      principalInfo: {}, //代理信息
      columns: [
        {
          title: messages('request-3.key27')/*代理人*/,
          dataIndex: 'proxyName',
          render: (value, record) => `${value} - ${record.emplyeeId}`
        },
        {
          title: messages('request-3.key7')/*代理日期*/,
          dataIndex: 'proxyTimeRange',
          render: (value, record) => {
            return (
              <div>
                {moment(record.startDate).format("YYYY-MM-DD")}
                {messages('request-3.key48')/*至*/}
                {value === 102 ? moment(record.endDate).format("YYYY-MM-DD") : messages('request-3.key13')/*无限制*/}
              </div>
            )
          }
        },
        {
          title: messages('request-3.key8')/*代理单据*/,
          dataIndex: 'proxyFormScope',
          render: (value, record) => value === 1001 ? messages('common.all')/*全部*/ : messages('request-3.key49')/*部分*/
        },
        {
          title: messages('common.column.status')/*状态*/,
          dataIndex: 'enabled',
          render: (value, record) => {
            return (
              <Badge
                status={value ? 'success': 'error'}
                text={value ? messages('request-3.key9')/*生效中*/ : messages('request-3.key10')/*已失效*/}
              />
            )
          }
        },
        {
          title: messages('common.operation')/*操作*/, dataIndex: 'operation', key: 'operation', align: "center", width: '10%',
          render: (value, record, index) => (
            <Popconfirm onConfirm={(e) => this.handleDelete(e, record, index)} title={messages('request-3.key12')/*你确认要删除？*/}>
              <a onClick={(e) => {e.preventDefault(); e.stopPropagation();}}>{messages('common.delete')/*删除*/}</a>
            </Popconfirm>
          )
        }
      ]
    };
    this.agencySetting = menuRoute.getRouteItem('agency-setting','key');   //代理设置
  }

  handleDelete = (e, record, index) =>{
    let { principalInfo } = this.state;
    let billProxyRuleDTOs = principalInfo.billProxyRuleDTOs;
    billProxyRuleDTOs.splice(index, 1);
    this.setState({ pageLoading: true });
    agencyService.newAgency(principalInfo).then(res => {
      message.success(messages('common.operate.success')/*操作成功*/);
      this.getInfo();
    }).catch(e => {
      this.setState({ pageLoading: false });
      errorMessage(e.response);
    });
  };

  componentDidMount() {
    this.getInfo();
  }

  //获取被代理人及代理关系信息
  getInfo= () => {
    const { principalOID } = this.props.params;
    const { location } = this.props;
    this.setState({ pageLoading: true });
    agencyService.getAgencyInfo(principalOID, location.query.tab === 'apply' ? 1 : 2).then(res =>{
      this.setState({
        pageLoading: false,
        principalInfo: res.data || {}
      });
    }).catch(e => {
      this.setState({ pageLoading: false });
      errorMessage(e.response);
    });
  };

  //返回
  handleBack = () => {
    const { location } = this.props;
    this.context.router.replace(this.agencySetting.url + `?tab=${location.query.tab}`);
  };

  handleNew = () => {
    const { location } = this.props;
    const { principalInfo } = this.state;
    let tab = location.query.tab;
    SlideFrame.open({
      title: tab === 'apply' ? messages('request-3.key50')/*新建代理制单规则*/ : messages('request-3.key51')/*新建代理审批规则*/,
      content: NewProxy,
      afterClose: this.handleCloseSlide,
      params: {
        tab,
        principalInfo
      }
    }, this);
  };

  handleRowClick = (record) => {
    const { location } = this.props;
    const { principalInfo } = this.state;
    let tab = location.query.tab;
    SlideFrame.open({
      title: tab === 'apply' ? messages('request-3.key52')/*编辑代理制单规则*/ : messages('request-3.key53')/*编辑代理审批规则*/,
      content: NewProxy,
      afterClose: this.handleCloseSlide,
      params: {
        tab,
        principalInfo,
        record
      }
    }, this);
  };

  handleCloseSlide = (success) => {
    success && this.getInfo();
  };

  render() {
    const { pageLoading, principalInfo, columns } = this.state;
    const { location } = this.props;
    let tab = location.query.tab;
    return (
      <div className="agency-detail-v2">
        <Spin spinning={pageLoading}>
          <div className="header-title">{messages('request-3.key54')/*代理详情*/}</div>
          <div className="block-content">
            <span>{messages('request-3.key55')/*被代理人：*/}</span>
            <span>{principalInfo.userName} - {principalInfo.emplyeeId}</span>
          </div>
          <div className="header-title">{messages('request-3.key56')/*代理规则设置*/}</div>
          {tab === 'apply' && (
            <div className="block-content" style={{color: '#989898'}}>{messages('request-3.key57')/*选择哪些员工可以帮被代理人提交单据，单据可按照被代理人的需求进行分配*/}</div>
          )}
          {tab === 'approve' && (
            <div className="block-content" style={{color: '#989898'}}>{messages('request-3.key58')/*选择哪些员工可以帮被代理人审批单据，单据可按照被代理人的需求进行分配*/}</div>
          )}
        </Spin>
        <Button type="primary" onClick={this.handleNew} style={{marginBottom: 10}}>
          {messages('common.create')/*新建*/}
        </Button>
        <ResizeTable
          rowKey="ruleOID"
          columns={columns}
          dataSource={principalInfo.billProxyRuleDTOs || []}
          pagination={false}
          onRow={record => ({onClick: () => this.handleRowClick(record)})}
          loading={pageLoading}
          bordered
          size="middle"
        />
        <div style={{marginTop: 15}}>
          <a className="back-icon" onClick={this.handleBack}>
            <Icon type="rollback" />{messages('common.back')/*返回*/}
          </a>
        </div>
      </div>
    )
  }
}

AgencyDetailV2.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps() {
  return {}
}

export default connect(mapStateToProps)(AgencyDetailV2);
